import {
  addTextFieldPropertiesToFeatures
} from '../../utils/LayerUtil';
import {
  formatDeviceFeature
} from '../../../../mapUtils/StyleListUtil';
import {
  parse
} from '../../../../mapUtils/Geojson2WktUtil';
import {
  projectLngLatToWebMercator
} from '../../../../mapUtils/CoordinateUtil';
import {
  debounce
} from 'throttle-debounce';

import IGridTool from '../IGridTool';
import Prefix from '../../constant/Prefix';

/**
 * 调度电网图层工具箱
 * @implements {IGridTool}
 */
class DispatchGridTool extends IGridTool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'DispatchGridTool';
    this.desc = '调度电网图层工具箱';
    this.layeridPrefix = Prefix['DispathGrid'];
    this.defaultSchemaid = 6;
    this._refresh = debounce(this.THROTTLE_DURATION, () => {
      this.refresh(this.useNewService, this.option);
    }).bind(this);
  }

  /**
   * 刷新现状图层
   * @override
   */
  refresh(useNewService, option) {
    this.option = option;
    this.setCurrentGridTool(this);
    if (this.isLocked()) {
      return;
    }
    // 当前请求时间
    let currentRequestTime = this.latestRequestTime = new Date().getTime();
    // 获取当前缩放等级下配置的图层列表
    this.getApi().PwghGhsjScTxfw.figure.get_figure_getEquitpType({
      params: {
        zoom: this.getTool('BaseMapTool').getZoom(),
        schemaid: this.searchOption.schemaid || this.defaultSchemaid
      }
    })
      .then((data) => {
        // 过期请求不处理
        if (this._isOutDate(currentRequestTime)) {
          return;
        }
        let sbzlxs = data.datas;
        let promiselist = [];
        // 获取范围、缩放等级
        let extent = this.getTool('BaseMapTool').getBounds();
        let shape =
          parse(
            turf.polygon(projectLngLatToWebMercator(turf.bboxPolygon(extent).geometry.coordinates)).geometry
          );
        // 拼接请求数据
        sbzlxs.forEach((sbzlx) => {
          promiselist.push(
            new Promise((resolve) => {
              let params = Object.assign(this.searchOption, {
                sblx: sbzlx.sblx,
                shape: shape,
                oid: sbzlx.oid
              });
              this.getApi().PwghGhsjScQygl.measureDataFlow.get_measureDataFlow_getSimpleFigureShow({
                params: params
              })
                .then((res) =>
                  resolve({
                    sblx: sbzlx.sblx,
                    res
                  })
                )
                .catch(() =>
                  resolve({
                    sblx: sbzlx.sblx,
                    res: {
                      datas: [],
                      'resp_msg': '调用服务出错'
                    }
                  })
                );
            })
          );
        });
        Promise.all(promiselist).then((resList) => {
          // 过期请求不处理
          if (!this._isOutDate(currentRequestTime)) {
            this._showBySgmapLayer(resList, option);
            this.finishRender();
          }
        });
      });
  }
  /**
   * 采用思极地图的形式绘制图层
   * @override
   * @param {Array} resList 图形数据
   * @ignore
   */
  _showBySgmapLayer(resList, option) {
    let features = [];
    let zoom = this.getTool('BaseMapTool').getZoom();
    console.log(option);
    let offset = option?.maxWidth ? Math.round(327680 / Math.pow(option.maxWidth, zoom)) : Math.round(327680 / Math.pow(2, zoom));
    console.log(offset);
    resList.forEach((res) => {
      if (res.res.resp_code !== 200) {
        return;
      }
      let sblx = res.sblx;
      let datas = res.res.datas || [];
      datas.forEach((item) => {
        let shapejson = item.shapejson;
        if (shapejson) {
          let lineNum = typeof item.sbzlx === 'string' ? item.sbzlx.split(',').length : 1;
          if (lineNum > 1) {
            let oid = item.oid.split(',');
            let sbzlx = item.sbzlx.split(',');
            let dydj = item.dydj.split(',');
            // let sbid = item.sbid.split(',');
            let sbmc = item.sbmc.split(',');
            let baseline = JSON.parse(shapejson);
            let offsetNum = (lineNum - 1) / 2;
            for (let i = 0, j = -offsetNum * offset; i < lineNum; i++, j = j + offset) {
              let line = Object.assign({}, item, {
                oid: oid[i],
                // sbzlx: this.formatSbzlx(sbzlx[i]),
                sbzlx: sbzlx[i],
                dydj: Number(dydj[i]),
                // sbid: sbid[i],
                sbmc: sbmc[i]
              });
              line.geometry = turf.lineOffset(baseline, j, { units: 'meters' }).geometry;
              // line.sblx = getSblxBySbzlx(line.sbzlx);
              // line.transSbzlx = line.sbzlx;
              line.sblx = sblx;
              line.transSbzlx = Number(line.sbzlx);
              // let style = getStyle(line, { zoom: zoom });
              let feature = formatDeviceFeature(line);
              features.push(feature);
            }
          } else {
            // item.sbzlx = this.formatSbzlx(item.sbzlx);
            item.dydj = Number(item.dydj);
            item.geometry = JSON.parse(shapejson);
            // item.sblx = getSblxBySbzlx(item.sbzlx);
            // item.transSbzlx = item.sbzlx;
            item.sblx = sblx;
            item.transSbzlx = Number(item.sbzlx);
            // let style = getStyle(item, { zoom: zoom });
            let feature = formatDeviceFeature(item);
            features.push(feature);
          }
        } else {
          // this.info(item.sbzlx, item.oid, "设备无返回坐标信息");
        }
      });
    });
    features = addTextFieldPropertiesToFeatures(features, 'sbmc');
    var featureCollection = turf.featureCollection(features);
    // 数据过滤器
    if(this.dataFilter) {
      featureCollection = this.dataFilter(featureCollection);
    }
    this.getMap().getSource(this._sourceId).setData(featureCollection);
    if(this.events.datachange) {
      this.events.datachange(this.getRenderedFeatures());
    }
    this.getEventBus().$emit('gridtool.datachange', this.getRenderedFeatures());
  }

  /**
   * 格式化设备子类型
   * @param {Array|Number} sbzlx 设备子类型
   * @ignore
   */
  formatSbzlx(sbzlx) {
    return Number(sbzlx.toString().substring(1));
  }
}

export default DispatchGridTool;